const slider = document.getElementById("slider");
const range = document.getElementById("slider-range");
const thumbMin = document.getElementById("thumb-min");
const thumbMax = document.getElementById("thumb-max");
const minInput = document.getElementById("min-input");
const maxInput = document.getElementById("max-input");

const min = 4.0;
const max = 20.0;
let minVal = min;
let maxVal = max;

// 百分比转像素位置
function valueToPercent (value) {
  return ((value - min) / (max - min)) * 100;
}

// 更新 UI
function updateUI () {
  const minPercent = valueToPercent(minVal);
  const maxPercent = valueToPercent(maxVal);

  thumbMin.style.left = minPercent + "%";
  thumbMax.style.left = maxPercent + "%";
  range.style.left = minPercent + "%";
  range.style.width = (maxPercent - minPercent) + "%";

  minInput.value = minVal.toFixed(2);
  maxInput.value = maxVal.toFixed(2);
}

// 拖动事件
function dragThumb (thumb, isMin) {
  let rect = slider.getBoundingClientRect();
  // 提高层级
  thumb.style.zIndex = 5;
  console.log(thumb);

  function onMove (e) {
    let x = e.clientX - rect.left;
    let percent = (x / rect.width) * 100;
    let value = min + (percent / 100) * (max - min);

    const minGap = 0.01; // 最小间距

    if (isMin) {
      if (value > maxVal - minGap) value = maxVal - minGap;
      if (value < min) value = min;
      minVal = value;
    } else {
      if (value < minVal + minGap) value = minVal + minGap;
      if (value > max) value = max;
      maxVal = value;
    }

    updateUI();
  }

  function onUp () {
    // 当前拖动的 thumb 保持较高层级
    thumb.style.zIndex = 5;

    // 找到另一个滑块，恢复默认层级
    const otherThumb = isMin ? thumbMax : thumbMin;
    otherThumb.style.zIndex = 1;

    document.removeEventListener("mousemove", onMove);
    document.removeEventListener("mouseup", onUp);
  }

  document.addEventListener("mousemove", onMove);
  document.addEventListener("mouseup", onUp);
}

thumbMin.addEventListener("mousedown", () => dragThumb(thumbMin, true));
thumbMax.addEventListener("mousedown", () => dragThumb(thumbMax, false));

// 输入框控制
minInput.addEventListener("blur", () => {
  let v = parseFloat(minInput.value);
  if (isNaN(v)) v = min;           // 非数字默认最小值
  if (v < min) v = min;            // 限制下界
  if (v >= maxVal) v = maxVal - 0.01; // 保持最小间距
  minVal = v;

  // z-index 处理
  thumbMin.style.zIndex = 5; // 当前滑块在上
  thumbMax.style.zIndex = 1; // 另一个滑块回默认

  updateUI();
});

maxInput.addEventListener("blur", () => {
  let v = parseFloat(maxInput.value);
  if (isNaN(v)) v = max;
  if (v > max) v = max;
  if (v <= minVal) v = minVal + 0.01;
  maxVal = v;

  // z-index 处理
  thumbMax.style.zIndex = 5; // 当前滑块在上
  thumbMin.style.zIndex = 1; // 另一个滑块回默认

  updateUI();
});


// 初始化
updateUI();